package com.idp.common.utils;

import com.idp.common.model.LoginInfo;
import com.idp.common.token.service.TokenService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 上下文工具类
 * @author King
 */
@Component
public class ContextUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

		ContextUtil.applicationContext = applicationContext;
	}

	/***
	 * 获取spring注入的类
	 * @param <T>
	 * @param clazz
	 * @return
	 */
	public static <T> T getBean(Class<T> clazz){

		return applicationContext.getBean(clazz);
	}

	/**
	 * 获取request
	 * @return
	 */
	public static HttpServletRequest getRequest() {

		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();

		return request;
	}

	public static String getLoginUserId() {

		TokenService tokenService = getBean(TokenService.class);

		LoginInfo loginInfo = tokenService.getLoginInfo();

		if(loginInfo != null) {

			return loginInfo.getId();
		}

		return null;
	}

	public static LoginInfo getLoginUser() {

		TokenService tokenService = getBean(TokenService.class);

		LoginInfo loginInfo = tokenService.getLoginInfo();

		if(loginInfo != null) {

			return loginInfo;
		}

		return null;
	}

	public static String getEnv() {

		Environment evn = applicationContext.getEnvironment();

		String[] envs = evn.getActiveProfiles();

		String env = "dev";

		for (String profile : envs) {
			if ("test".equals(profile)){
				env = "test";
				break;
			} else if ("prod".equals(profile)){
				env = "prod";
				break;
			}
		}

		return env;
	}

}
